package com.yazdankhah.dal;

import com.yazdankhah.utils.TextDataTools;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Level;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.apache.log4j.Logger;

/**
 *
 * @author ahmad
 */
public class DalSession {
  
  private static DataSource ds;
  
  private static DalSession dSession;
  
  private static final Logger logger = Logger.getLogger(DalSession.class);
  
  private DalSession() {
    setDatasource();
    
  } //constructor
  
  
  /**
   * Give the user of this class a singleton object of this class.
   * @return a singleton object of this class
   */
  public static DalSession getDalSession() {
    
    if (dSession == null)
      dSession = new DalSession();
    
    return dSession;
  } //method
  
  
  public Connection getDSConnection() {
    
    Connection conn = null;
    
    try {
      if (ds == null) throw new SQLException("Datasource is null! Can't get data source");
      
      conn = ds.getConnection("root", "sesame");
      
      if (conn == null) throw new SQLException("Can't get connection from the datasource!");
      
    } catch (SQLException e) {
      logger.error("Couldn't get a connection from datasource!");
      logger.debug("SQLException due to: " + e.getMessage());
    }
    
    return conn;
    
  } //method
  
  
  public Connection getTransaction() {
    
    try {
      Connection conn = getDSConnection();
      
      conn.setAutoCommit(false);
      return conn;
      
    } catch (SQLException ex) {
      logger.fatal("SQLException during getTransaction due to: " + ex.getMessage());
      return null;
    }
    
  } //method
  
  
  public boolean closeTransaction(Connection conn) {
    
    try {
      conn.setAutoCommit(true);
      
      return SqlUtil.freeResource(conn);
      
    } catch (SQLException ex) {
      logger.fatal("SQLException during closeTransaction due to: " + ex.getMessage());
      return false;
    }
    
  } //method
  
  
  public boolean closeConnection(Connection conn) {
    
    return SqlUtil.freeResource(conn);
  } //method
  
  
  private static void setDatasource() {
    try {
      if (ds == null) {
        Context ctx = new InitialContext();
        ds = (DataSource) ctx.lookup(TextDataTools.lookupConfig("app.datasource.name"));
      }
    }
    catch (NamingException ex) {
      logger.fatal("NamingException due to: " + ex.getMessage());
    }
  } //method
  
} //class
